<?php
/**
 * Created by PhpStorm.
 * User: Anthony Qu
 * Date: 2017/1/28
 * Time: 下午4:17
 */

namespace App\Traits;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Facades\Image;
use Symfony\Component\HttpFoundation\File\File;

/**
 * 文件上传协助
 * Class FileUploadTrait
 * @package App\Traits
 */
trait FileUploadTrait
{
    protected $uploadObj;
    protected $uploadOptions;
    protected $relativePath;
    protected $fileUploadError = 0;

    public function upload(UploadedFile $file, $options = [])
    {
        $this->uploadObj = $file;

        if (0 === $this->uploadObj->getError()) {
            if (!empty($options)) {
                $this->uploadOptions = $options;
            }

            $file = $this->uploadOne();

            return $file;
        }

        return false;
    }

    protected function uploadOne()
    {
        $newFileName = $this->createNewName();
        $createDir = $this->createDir();
        $this->relativePath = $this->relativePath . '/' . $newFileName;
        $file = $this->uploadObj->move($createDir, $newFileName);
        $file->savePath = $this->relativePath;

        if (isset($this->uploadOptions['resize'])) {
            $file = $this->setResize($this->uploadOptions['resize'], $file);
        }

        return $file;
    }

    protected function setResize($resize, $file)
    {
        $realPath = $file->getRealPath();
        $width = $resize['width'];
        $height = $resize['height'];
        $img = Image::make($realPath);
        $thumbPrefix = isset($this->uploadOptions['thumb']) ? $this->uploadOptions['thumb'] : '';
        // 如果等比例
        if (isset($resize['proportion']) && true === $resize['proportion']) {
            $img->width() > $img->height() ? $width = null : $height = null;
        }

        $fileName = $file->getFileName();
        $file->savePath = str_replace($fileName, $thumbPrefix . $fileName, $file->savePath);
        $thumbUrl = str_replace($fileName, $thumbPrefix . $fileName, $realPath);

        $img->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
        })->save($thumbUrl);

        return $file;
    }

    protected function uploadAll()
    {
        // todo...多文件上传
    }

    protected function createDir()
    {
        $uploadPath = isset($this->uploadOptions['upload_path']) ? $this->uploadOptions['upload_path'] : '';
        $this->relativePath = $dirStructure = isset($this->uploadOptions['dir_structure']) ? $this->uploadOptions['dir_structure'] : '';

        return $uploadPath . $this->relativePath;
    }

    protected function createNewName()
    {
        $newFilePrefix = isset($this->uploadOptions['prefix']) ? $this->uploadOptions['prefix'] : '';
        $fileSuffix = $this->uploadObj->getClientOriginalExtension();
        $newFileName = uniqid($newFilePrefix) . '.' . $fileSuffix;

        return $newFileName;
    }

    // todo...多文件上传
}